import 'package:flutter/material.dart';
import 'package:flutter_base/src/routes/common_routes.dart';
import 'package:flutter_base/src/routes/home_routes.dart';
import 'package:flutter_base/src/utils/navigation_service.dart';
import 'package:go_router/go_router.dart';

/// 应用路由
class AppRoutes {
  // 路由观察者
  static final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

  /// 路由配置
  static GoRouter router = GoRouter(
    initialLocation: HomeRoutes.homePath,
    navigatorKey: NavigationService.navigatorKey,
    observers: [routeObserver, MyRouteObserver()],
    errorBuilder: (context, state) {
      return Scaffold(
        appBar: AppBar(title: Text('404')),
        body: Center(child: Text('404', style: const TextStyle(fontSize: 20))),
      );
    },
    routes: [
      // 首页相关路由
      ...HomeRoutes.routes,
      // 通用路由
      ...CommonRoutes.routes,
    ],
  );
}

class MyRouteObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    FocusScope.of(NavigationService.context).unfocus();
    FocusManager.instance.primaryFocus?.unfocus();
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    FocusScope.of(NavigationService.context).unfocus();
    FocusManager.instance.primaryFocus?.unfocus();
  }
}
